package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.enums.TxnType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WdyDirectReward;
import com.ruoyi.system.domain.WdyReferrerReward;
import com.ruoyi.system.domain.WdyTxnHistory;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.mapper.WdyReferrerRewardMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.IWdyReferrerRewardService;
import com.ruoyi.system.service.IWdyTxnHistoryService;
import com.ruoyi.system.service.IWdyUserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 推荐奖励 服务层实现
 * 
 * @author ruoyi
 * @date 2019-12-26
 */
@Service
public class WdyReferrerRewardServiceImpl extends ServiceImpl<WdyReferrerRewardMapper, WdyReferrerReward> implements IWdyReferrerRewardService
{
	@Autowired
	private IWdyUserService wdyUserService;
	@Autowired
	private IWdyTxnHistoryService wdyTxnHistoryService;
	@Autowired
	private ISysConfigService sysConfigService;
	/**
     * 查询推荐奖励信息
     * 
     * @param id 推荐奖励ID
     * @return 推荐奖励信息
     */
    @Override
	public WdyReferrerReward selectWdyReferrerRewardById(Long id)
	{
	    return baseMapper.selectWdyReferrerRewardById(id);
	}
	
	/**
     * 查询推荐奖励列表
     * 
     * @param wdyReferrerReward 推荐奖励信息
     * @return 推荐奖励集合
     */
	@Override
	public List<WdyReferrerReward> selectWdyReferrerRewardList(WdyReferrerReward wdyReferrerReward)
	{
	    return baseMapper.selectWdyReferrerRewardList(wdyReferrerReward);
	}
	
    /**
     * 新增推荐奖励
     * 
     * @param wdyReferrerReward 推荐奖励信息
     * @return 结果
     */
	@Override
	public int insertWdyReferrerReward(WdyReferrerReward wdyReferrerReward)
	{
	    return baseMapper.insertWdyReferrerReward(wdyReferrerReward);
	}
	
	/**
     * 修改推荐奖励
     * 
     * @param wdyReferrerReward 推荐奖励信息
     * @return 结果
     */
	@Override
	public int updateWdyReferrerReward(WdyReferrerReward wdyReferrerReward)
	{
	    return baseMapper.updateWdyReferrerReward(wdyReferrerReward);
	}

	/**
     * 删除推荐奖励对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWdyReferrerRewardByIds(String ids)
	{
		return baseMapper.deleteWdyReferrerRewardByIds(Convert.toStrArray(ids));
	}


	@Transactional(rollbackFor = Exception.class)
	@Override
	public void rewardRecharge(String userId, BigDecimal txnAmount, Long txnId) {
		if(!"1".equals(sysConfigService.selectConfigByKey("recharge_teamreward_state"))){
			return;
		}
		BigDecimal teamrewardRatio = new BigDecimal(sysConfigService.selectConfigByKey("recharge_teamreward_ratio"));
		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("referrer_id");
		queryWrapper.eq("user_id", userId);
		WdyUser user = wdyUserService.getOne(queryWrapper);
		String referrerId = user.getReferrerId();
		while(StringUtils.isNotEmpty(referrerId)) {
			queryWrapper = new QueryWrapper<>();
			queryWrapper.select("user_id", "referrer_id", "level", "cnn_withdraw_amount", "version");
			queryWrapper.eq("user_id", referrerId);
			WdyUser referrerUser = wdyUserService.getOne(queryWrapper);
			if(referrerUser == null) {
				break;
			}
			if(referrerUser.getLevel() > 0) {
				BigDecimal rewardAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.multiply(txnAmount, teamrewardRatio));
				if(rewardAmount.compareTo(BigDecimal.ZERO) > 0) {
					WdyReferrerReward wdyReferrerReward = new WdyReferrerReward();
					wdyReferrerReward.setUserId(referrerUser.getUserId());
					wdyReferrerReward.setLevelDiffReward(rewardAmount);
					wdyReferrerReward.setCreateBy(userId);
					this.save(wdyReferrerReward);

					WdyUser updateUser = new WdyUser();
					updateUser.setCnnWithdrawAmount(BigDecimalUtil.add(referrerUser.getCnnWithdrawAmount(), rewardAmount));
					updateUser.setVersion(referrerUser.getVersion());
					if(!wdyUserService.update(updateUser, queryWrapper)) {
						throw new BusinessException(ResultConstants.FI2007, "系统繁忙，请稍后重试");
					}

					WdyTxnHistory txnHistory = new WdyTxnHistory();
					txnHistory.setUserId(referrerUser.getUserId());
					txnHistory.setTxnId(String.valueOf(txnId));
					txnHistory.setTxnAmount(rewardAmount);
					txnHistory.setTxnType(TxnType.TEAM_REWARD.getCode());
					txnHistory.setAmountType(TxnType.TEAM_REWARD.getAmountType().getCode());
					String typeStr = "充值";
					txnHistory.setTxnDesc(typeStr + TxnType.TEAM_REWARD.getName());
					wdyTxnHistoryService.save(txnHistory);
				}
				break;
			}
			referrerId = referrerUser.getReferrerId();
		}
	}


	@Transactional(rollbackFor = Exception.class)
	@Override
	public void reward(String userId, BigDecimal txnAmount, Long txnId, int type) {
		if(!"1".equals(sysConfigService.selectConfigByKey("teamreward_state"))){
			return;
		}
		JSONArray ratioArray = JSONArray.parseArray(sysConfigService.selectConfigByKey("teamreward_ratio"));
		int preMaxLevel = 0;
		double preRatio = 0;
		List<WdyReferrerReward> rewardList = new ArrayList<>();
		List<WdyTxnHistory> txnList = new ArrayList<>();
		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("referrer_id");
		queryWrapper.eq("user_id", userId);
		WdyUser user = wdyUserService.getOne(queryWrapper);
		String referrerId = user.getReferrerId();
		while(StringUtils.isNotEmpty(referrerId)) {
			queryWrapper = new QueryWrapper<>();
			queryWrapper.select("user_id", "referrer_id", "level", "cnn_withdraw_amount", "version");
			queryWrapper.eq("user_id", referrerId);
			WdyUser referrerUser = wdyUserService.getOne(queryWrapper);
			if(referrerUser == null) {
				break;
			}
			if(referrerUser.getLevel() > preMaxLevel) {
				double curRatio = ratioArray.getDoubleValue(referrerUser.getLevel());
				double ratio = curRatio - preRatio;
				BigDecimal rewardAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.multiply(txnAmount, ratio));
				if(rewardAmount.compareTo(BigDecimal.ZERO) > 0) {
					WdyReferrerReward wdyReferrerReward = new WdyReferrerReward();
					wdyReferrerReward.setUserId(referrerUser.getUserId());
					wdyReferrerReward.setLevelDiffReward(rewardAmount);
					wdyReferrerReward.setCreateBy(userId);
					rewardList.add(wdyReferrerReward);

					WdyUser updateUser = new WdyUser();
					updateUser.setCnnWithdrawAmount(BigDecimalUtil.add(referrerUser.getCnnWithdrawAmount(), rewardAmount));
					updateUser.setVersion(referrerUser.getVersion());
					if(!wdyUserService.update(updateUser, queryWrapper)) {
						throw new BusinessException(ResultConstants.FI2007, "系统繁忙，请稍后重试");
					}

					WdyTxnHistory txnHistory = new WdyTxnHistory();
					txnHistory.setUserId(referrerUser.getUserId());
					txnHistory.setTxnId(String.valueOf(txnId));
					txnHistory.setTxnAmount(rewardAmount);
					txnHistory.setTxnType(TxnType.TEAM_REWARD.getCode());
					txnHistory.setAmountType(TxnType.TEAM_REWARD.getAmountType().getCode());
					String typeStr = type == WdyDirectReward.RECHARGE ? "充值" : "理财";
					txnHistory.setTxnDesc(typeStr + TxnType.TEAM_REWARD.getName());
					txnList.add(txnHistory);
				}

				preMaxLevel = referrerUser.getLevel();
				preRatio = curRatio;
			}
			referrerId = referrerUser.getReferrerId();
		}
		if(CollectionUtils.isNotEmpty(rewardList)) {
			this.saveBatch(rewardList);
		}
		if(CollectionUtils.isNotEmpty(txnList)) {
			wdyTxnHistoryService.saveBatch(txnList);
		}
	}
}
